﻿using System;
using Dexter.CallContext;
using Dexter.Logger.Contracts;

namespace Dexter.Async.Executor {
	public class AsyncExecutor : IAsyncExecutor {
		readonly IDexterCall dexterCall;
		readonly ILogger logger;

		/// <summary>
		/// Initializes a new instance of the <see cref="T:System.Object"/> class.
		/// </summary>
		public AsyncExecutor ( IDexterCall dexterCall , ILogger logger ) {
			this.dexterCall = dexterCall;
			this.logger = logger;
		}

		#region IAsyncExecutor Members

		public void Execute ( InvocationToken token ) {
			try {
				dexterCall.StartSession(token.IsReadOnly);
				token.Invoke ( );
				token.AsyncResult.SetAsCompleted ( null, false );
				dexterCall.Complete ( true );
			}
			catch (Exception ex) {
				logger.Error ( "Error during async call", ex );
				token.AsyncResult.SetAsCompleted ( ex, false );
				dexterCall.Complete ( false );
				throw;
			}
		}

		#endregion
	}
}